package mongo;

import org.bson.BsonReader;
import org.bson.BsonType;
import org.bson.BsonWriter;
import org.bson.codecs.Codec;
import org.bson.codecs.DecoderContext;
import org.bson.codecs.EncoderContext;
import org.bson.types.ObjectId;

/**
 * @author : zGame
 * @version V1.0
 * @Project: mongo-java-demo
 * @Package mongo
 * @Description: 自定义加解码器
 * @date Date : 2022年02月08日 17:36
 */
public class PlayerCodec implements Codec<Player> {
    
    @Override
    public  Player decode(BsonReader bsonReader, DecoderContext decoderContext) {
        bsonReader.readStartDocument();
        Player p = new Player();
        while (bsonReader.readBsonType() != BsonType.END_OF_DOCUMENT) {
            String fieldName = bsonReader.readName();
            if (fieldName.equals("_id")) {
                ObjectId id = bsonReader.readObjectId();
                p.setId(id);
            }else if(fieldName.equals("userName")){
                p.setUserName(bsonReader.readString());
            }else if(fieldName.equals("channel")){
                p.setChannel(bsonReader.readString());
            }
        }
        bsonReader.readEndDocument();
        return p;
    }
    
    @Override
    public void encode(BsonWriter bsonWriter, Player player, EncoderContext encoderContext) {
    
        System.out.println("encode");
    }
    
    @Override
    public Class<Player> getEncoderClass() {
        return Player.class;
    }
}
